package com.yw.smartcityforjava.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yw.smartcityforjava.App;
import com.yw.smartcityforjava.R;
import com.yw.smartcityforjava.api.Api;
import com.yw.smartcityforjava.api.ICallback;
import com.yw.smartcityforjava.api.login.LoginRequest;
import com.yw.smartcityforjava.api.login.LoginResponse;
import com.yw.smartcityforjava.api.ServiceCreator;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText etAccount;
    private EditText etPwd;
    private Button btnLogin;
    private TextView register;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = etAccount.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();

                if(TextUtils.isEmpty(account)){
                    Toast.makeText(App.app, "请输入账号", Toast.LENGTH_LONG).show();
                    return;
                }
                if(TextUtils.isEmpty(pwd)){
                    Toast.makeText(App.app, "请输入密码", Toast.LENGTH_LONG).show();
                    return;
                }

                //请求服务器登录
                loginRequest(account,pwd);
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                //finish();
            }
        });

        //loginRequest("yw","123456");

    }

    private void initView(){
        etAccount = (EditText) findViewById(R.id.et_account);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        btnLogin = (Button) findViewById(R.id.btn_login);
        register = findViewById(R.id.registerTv);
    }

    private void loginRequest(String account, String pwd){
        ServiceCreator.getInstance().getApi().login(new LoginRequest(account, pwd)).enqueue(new ICallback<LoginResponse>() {

            @Override
            public void onSuccess(LoginResponse response) {
                Log.d("network", "token = " + response.getToken());
                App.token = response.getToken();
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }
        });
    }


}